package com.lishe.lishe.lishe.widget;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.fynn.fluidlayout.FluidLayout;
import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.mall.bean.SkuObject;
import com.lishe.lishe.lishe.module.mall.fragment.GoodsDetailFragent;
import com.lishe.lishe.lishe.module.mall.http.HttpMall;
import com.lishe.lishe.lishe.module.mall.view.GoodsAddressDialog;
import com.lishe.lishe.lishe.bean.AddressItem;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.utils.LogUtil;
import com.lishe.lishe.lishe.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by shino on 2017/9/20.
 * & Bin (改成dialog)
 * 地址选择的popupwindow
 */

public class GoodsProDialog extends Dialog implements View.OnClickListener {
    //区分 加入购物车/已选
    public static final int FROM_HADCHOSE = -1;
    public static final int FROM_ADDSHOPCAR = -2;

    private Activity mContext;
    private int mFrom, mGoodStatus;
    private List<AddressItem> mAddressList;
    private List<SkuObject> mSkuList = new ArrayList<>();
    private List<TextView> skuTextViwes = new ArrayList<>();
    private String mPrice;
    private String imgUrl;
    private int mGoodsCount = 1;

    private TextView mTvSelectAddress;
    private View mAddressLayout;

    private int checkSkuIndex = 0;//sku栏选中标志
    private GoodsAddressDialog mAddressDialog;
    private TextView mSelect;
    private Button mBtnSure;
    private AlertDialog mTipDialog;
    private int mAddressIndex = 0;//地址栏选中标志
    private String shop_id, item_id;
    private View mRedus;
    private View mAugment;
    private View mRedusLayout;
    private View mAugmentLayout;
    private TextView mTvCount;

    public GoodsProDialog(Activity context, int from, int status) {
        super(context, R.style.SimpleBottomDialog);
        this.mContext = context;
        this.mFrom = from;
        this.mGoodStatus = status;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.item_popupwidow_add_goods);
        Window dialogWindow = getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        Display display = dialogWindow.getWindowManager().getDefaultDisplay();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = display.getWidth();
        dialogWindow.setAttributes(lp);

        //设置点击Dialog外部任意区域关闭Dialog
        setCanceledOnTouchOutside(true);
        init();
    }

    public void resetAddressData(List<AddressItem> list) {
        mAddressList = list;
        //ui
        if (mAddressList.size() == 0) {
            mBtnSure.setEnabled(false);
            mBtnSure.setBackgroundColor(mContext.getResources().getColor(R.color.gray_9));
        } else {
            mBtnSure.setEnabled(true);
            mBtnSure.setBackgroundColor(mContext.getResources().getColor(R.color.color_ff4138));
            mAddressList.get(0).setCheck(true);
            String address = mAddressList.get(0).getArea() + mAddressList.get(0).getAddr();
            mTvSelectAddress.setText(address);
            itemOnclickListener.onAddressItemOnclickListener(address, 0);
            if (mGoodStatus == GoodsDetailFragent.ONSALE) {
                checkSku();
            }
        }
        if (mGoodStatus == GoodsDetailFragent.INSTOCK) {
            mBtnSure.setText("商品已下架");
            mBtnSure.setEnabled(false);
            mBtnSure.setBackgroundColor(mContext.getResources().getColor(R.color.gray_9));

            mRedusLayout.setEnabled(false);
            mAugmentLayout.setEnabled(false);
            mTvCount.setEnabled(false);
            mTvCount.setText("0");
        }

        if (mAddressDialog != null && mAddressDialog.isShowing()) {
            mAddressDialog.dismiss();
            //mAddressDialog.resetData(mAddressList);
        }
    }

    //设置地址数组
    public void setAddressList(List<AddressItem> list) {
        mAddressList = list;
    }

    //添加sku
    public void setSku(List<SkuObject> addSkus) {
        this.mSkuList.clear();
        this.mSkuList.addAll(addSkus);
    }

    //商品数量
    public void setCount(int count) {
        mGoodsCount = count;
    }

    //价格
    public void setPrice(String price) {
        this.mPrice = price;
    }

    //折前积分
    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }

    public void setShop_id(String shop_id) {
        this.shop_id = shop_id;
    }

    public void setItem_id(String item_id) {
        this.item_id = item_id;
    }


    /**
     * 初始化视图
     */
    private void init() {
        skuTextViwes.clear();
        //---------------------列表栏----------------------
        FluidLayout skuLayout = findViewById(R.id.sku_layout);
        mTvSelectAddress = findViewById(R.id.select_address);
        mAddressLayout = findViewById(R.id.address_layout);
        mAddressLayout.setOnClickListener(this);
        //---------------------图片及常量----------------------
        View close = findViewById(R.id.close);
        TextView mTvPrice = findViewById(R.id.price);
        mSelect = findViewById(R.id.select);
        ImageView goods_img = findViewById(R.id.goods_image);
        mTvCount = findViewById(R.id.count);
        mRedus = findViewById(R.id.redus);
        mRedusLayout = findViewById(R.id.redus_layout);
        mAugment = findViewById(R.id.augment);
        mAugmentLayout = findViewById(R.id.augment_layout);
        mBtnSure = findViewById(R.id.sure);
        //------------------------初始化数据------------------------
        if (imgUrl != null) {
            ImageLoaderUtils.displayImage(mContext,imgUrl, goods_img);
        }
        mTvPrice.setText("¥" + mPrice);

        if (mFrom == FROM_HADCHOSE) {
            mBtnSure.setText(R.string.add_into_shoppint_cart);
        } else if (mBtnSure != null && mFrom == FROM_ADDSHOPCAR) {
            mBtnSure.setText(R.string.sure1);
        }

        if (mAddressList.size() == 0) {
            mBtnSure.setEnabled(false);
            mBtnSure.setBackgroundColor(mContext.getResources().getColor(R.color.gray_9));
        } else {
            mBtnSure.setEnabled(true);
            mBtnSure.setBackgroundColor(mContext.getResources().getColor(R.color.color_ff4138));
            for (int i = 0; i < mAddressList.size(); i++) {
                if (mAddressList.get(i).isCheck()) {
                    String address = mAddressList.get(i).getArea() + mAddressList.get(i).getAddr();
                    mTvSelectAddress.setText(address);
                    itemOnclickListener.onAddressItemOnclickListener(address, i);
                    mAddressIndex = i;
                }
            }
            if (mGoodStatus == GoodsDetailFragent.ONSALE) {
                checkSku();
            }
        }
        if (mGoodStatus == GoodsDetailFragent.INSTOCK) {
            mBtnSure.setText("商品已下架");
            mBtnSure.setEnabled(false);
            mBtnSure.setBackgroundColor(mContext.getResources().getColor(R.color.gray_9));

            mRedusLayout.setEnabled(false);
            mAugmentLayout.setEnabled(false);
            mTvCount.setEnabled(false);
            mTvCount.setText("0");
        }
        //------------------------监听------------------------
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });

        //减
        mRedusLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mGoodsCount > 1) {
                    mGoodsCount -= 1;
                    mTvCount.setText(mGoodsCount + "");
                }
            }
        });

        //加
        mAugmentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mGoodsCount += 1;
                mTvCount.setText(mGoodsCount + "");
            }
        });

        /*mTvCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new GoodsNumDialog(mContext, mGoodsCount, new GoodsNumDialog.SureClicker() {
                    @Override
                    public void onSureClick(int num) {
                        //通过键盘输入0时，保存自动改为1
                        if (0 == num) {
                            mGoodsCount = 1;
                            mTvCount.setText(mGoodsCount + "");
                        }  else if (mSkuList.get(checkSkuIndex).getStore() <= 0) {
                            //通过键盘输入最大值时，保存自动改为最大值
                            mGoodsCount = 1;
                            mTvCount.setText(mGoodsCount + "");
                        } else if (num <= mSkuList.get(checkSkuIndex).getStore()) {
                            mGoodsCount = num;
                            mTvCount.setText(mGoodsCount + "");
                        } else if (num > mSkuList.get(checkSkuIndex).getStore()) {
                                //tip
                                if (mTipDialog == null) {
                                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.MyTransparentDialog);
                                    builder.setView(R.layout.dialog_overcount_tip);
                                    mTipDialog = builder.create();
                                    Window win = mTipDialog.getWindow();
                                    WindowManager.LayoutParams params = new WindowManager.LayoutParams();
                                    params.y = 300;//设置y轴偏移量
                                    win.setAttributes(params);
                                }
                                if (mTipDialog != null && !mTipDialog.isShowing()) {
                                    mTipDialog.show();
                                }
                                mGoodsCount = mSkuList.get(checkSkuIndex).getStore();
                                mTvCount.setText(mGoodsCount + "");
                            }
                    }
                }).show();
            }
        });*/

        //添加TextWatcher
        mTvCount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                //数量为1时，减号为灰，点击无反应。
                if (mGoodsCount == 1) {
                    mRedusLayout.setClickable(false);
                    mRedus.setBackgroundResource(R.mipmap.sub1);
                } else {
                    mRedusLayout.setClickable(true);
                    mRedus.setBackgroundResource(R.mipmap.sub);
                }

                //数量上限时，此时加号变灰不可点击
                if (mGoodsCount >= mSkuList.get(checkSkuIndex).getStore()) {
                    mAugmentLayout.setClickable(false);
                    mAugment.setBackgroundResource(R.mipmap.add1);
                } else {
                    mAugmentLayout.setClickable(true);
                    mAugment.setBackgroundResource(R.mipmap.add);
                }
            }
        });

        //确定
        mBtnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (itemOnclickListener != null) {
                    itemOnclickListener.onComfitOnclickListener(mGoodsCount);
                }
            }
        });
        mTvCount.setText("" + mGoodsCount);

        //-----------------------动态生成规格view-------------------------
        skuLayout.removeAllViews();
        addSkuView(skuLayout);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.address_layout:
                if (mAddressList.size() == 0) {
                    itemOnclickListener.onAddAddress();
                } else {
                    mAddressDialog = new GoodsAddressDialog(mContext, mAddressList, new GoodsAddressDialog.SelectListener() {
                        @Override
                        public void onSelect(int position) {
                            if (position == mAddressIndex) {
                                return;
                            }

                            mAddressIndex = position;
                            //找出选择的地址item 赋值并更新ui
                            mTvSelectAddress.setText(mAddressList.get(position).getArea() + mAddressList.get(position).getAddr());
                            itemOnclickListener.onAddressItemOnclickListener(mAddressList.get(position).getArea() + mAddressList.get(position).getAddr(), position);
                            if (mGoodStatus == GoodsDetailFragent.ONSALE) {
                                checkSku();
                            }
                        }

                        @Override
                        public void onNewAddress() {
                            itemOnclickListener.onAddAddress();
                        }
                    });
                    mAddressDialog.show();
                }
                break;
        }
    }

    /**
     * 检测商品库存
     */
    private void checkSku() {
        if (mAddressList.size() == 0) {
            return;
        }
        LoadingUtils.createLoadingDialog(mContext, "正在获取库存", true).show();
        String addressID = mAddressList.get(mAddressIndex).getArea_id();
        String skuId = mSkuList.get(checkSkuIndex).getSku_id();
        LogUtil.i("111111111111", Globals.getToken() + ",,,,," + addressID + ",,,,," + skuId + ",,,,," + shop_id + ",,,,," + item_id);
        HttpMall.checkSKU(Globals.getToken(), addressID, skuId, shop_id, item_id, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String result = new String(responseBody);
                LogUtil.i("检测商品库存", result);
                try {
                    JSONObject json = new JSONObject(result);
                    if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                        JSONObject dataObject = json.optJSONObject("data");
                        mSkuList.get(checkSkuIndex).setStore(dataObject.optInt("numDiff"));
                        if (dataObject.optInt("numDiff") > 0) {
                            if (mFrom == FROM_HADCHOSE) {
                                mBtnSure.setText(R.string.add_into_shoppint_cart);
                            } else if (mBtnSure != null && mFrom == FROM_ADDSHOPCAR) {
                                mBtnSure.setText(R.string.sure1);
                            }
                            mBtnSure.setEnabled(true);
                            mBtnSure.setBackgroundColor(mContext.getResources().getColor(R.color.color_ff4138));
                        } else {
                            mBtnSure.setText("该地区无货");
                            mBtnSure.setEnabled(false);
                            mBtnSure.setBackgroundColor(mContext.getResources().getColor(R.color.gray_9));

                            mTvCount.setText("1");
                        }
                    } else {
                        /*String msg = json.optString("msg");
                        ToastUtil.showToast(mContext, msg);*/
                        mBtnSure.setText("该地区无货");
                        mBtnSure.setEnabled(false);
                        mBtnSure.setBackgroundColor(mContext.getResources().getColor(R.color.gray_9));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    LoadingUtils.closeDialog();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                LoadingUtils.closeDialog();
                ToastUtil.showToast(mContext, mContext.getString(R.string.network_or_server_exception));
            }
        });
    }

    /**
     * 动态生成skuView
     *
     * @param skuLayout
     */
    private void addSkuView(FluidLayout skuLayout) {
        for (int i = 0; i < mSkuList.size(); i++) {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            View view = inflater.inflate(R.layout.item_shape_textviwe50px, null);
            final TextView spec = view.findViewById(R.id.spec);
            if (TextUtils.isEmpty(mSkuList.get(i).getSpec_info())) {
                spec.setText("默认规格");
                mSkuList.get(i).setSpec_info("默认规格");
            } else {
                spec.setText(mSkuList.get(i).getSpec_info());
            }
            //选中展示
            if (i == checkSkuIndex) {
                mSelect.setText("已选：“" + mSkuList.get(checkSkuIndex).getSpec_info() + "”");
                spec.setBackgroundResource(R.drawable.shape_coner50px_ff4138);
                spec.setTextColor(mContext.getResources().getColor(R.color.color_ff4138));
                itemOnclickListener.onSkuItemOnclickListener(false, mSkuList.get(checkSkuIndex).getSku_id());
            }
            spec.setTag(i);
            final int finalI = i;
            spec.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    skuTextViwes.get(checkSkuIndex).setBackgroundResource(R.drawable.shape_coner50px);
                    skuTextViwes.get(checkSkuIndex).setTextColor(mContext.getResources().getColor(R.color.gray_9));
                    checkSkuIndex = ((Integer) spec.getTag());
                    skuTextViwes.get(checkSkuIndex).setBackgroundResource(R.drawable.shape_coner50px_ff4138);
                    skuTextViwes.get(checkSkuIndex).setTextColor(mContext.getResources().getColor(R.color.color_ff4138));
                    mSelect.setText("已选：“" + mSkuList.get(finalI).getSpec_info() + "”");
                    itemOnclickListener.onSkuItemOnclickListener(false, mSkuList.get(finalI).getSku_id());

                    //数量上限时，此时加号变灰不可点击
                    if (mGoodsCount >= mSkuList.get(checkSkuIndex).getStore()) {
                        mAugmentLayout.setClickable(false);
                        mAugment.setBackgroundResource(R.mipmap.add1);
                    } else {
                        mAugmentLayout.setClickable(true);
                        mAugment.setBackgroundResource(R.mipmap.add);
                    }

                    if (mGoodStatus == GoodsDetailFragent.ONSALE) {
                        checkSku();
                    }
                }
            });
            skuTextViwes.add(spec);
            skuLayout.addView(view);
        }
    }

    /**
     * 回调事件
     */
    ItemOnclickListener itemOnclickListener;

    public interface ItemOnclickListener {
        void onAddressItemOnclickListener(String address, int position);//地址点击监听

        void onSkuItemOnclickListener(boolean isDefalut, String skuId);//sku点击监听

        void onComfitOnclickListener(int count);//确认按钮点击监听

        void onAddAddress();//新增收货地址
    }

    public void setOnItemOnclickListener(ItemOnclickListener itemOnclickListener) {
        this.itemOnclickListener = itemOnclickListener;
    }

}
